import os
import allure
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from ..util.log_util import root_path,logger


class Base:     # 基础
    def __init__(self, driver=None):    # 如果未使用,则定义.使用之后,获取之前的driver
        if driver:
            self.driver = driver
        else:
            self.driver = webdriver.Edge()
            self.driver.implicitly_wait(10)
            self.driver.maximize_window()

    def find(self, by):
        el = self.driver.find_element(*by)
        return el

    def find_click(self, by):   # 单个点击按钮
        logger.debug(f'定位"{by[0]}",元素"{by[1]}"')
        el = self.driver.find_element(*by)
        el.click()

    def finds_click(self, by, num):     # 多个点击按钮
        logger.debug(f'定位"{by[0]}[{num}]",元素"{by[1]}"')
        el = self.driver.find_elements(*by)[num]
        el.click()

    def find_key(self, by, key):    # 单个输入框
        logger.debug(f'定位"{by[0]}",元素"{by[1]}",输入值"{key}"')
        el = self.driver.find_element(*by)
        el.send_keys(key)

    def finds_key(self, by, num, key):      # 多个输入框
        logger.debug(f'定位"{by[0]}[{num}]",元素"{by[1]}",输入值"{key}"')
        el = self.driver.find_elements(*by)[num]
        el.send_keys(key)

    def find_text(self, by):    # 获取text
        logger.debug(f'获取 定位"{by[0]}",元素"{by[1]}" 的text')
        el = self.find(by)
        return el.text

    def wait(self, method, time_out=5):     # 显式等待
        logger.debug("显式等待中")
        el = WebDriverWait(self.driver, time_out).until(expected_conditions.visibility_of_element_located(method))
        return el

    def images_log(self, img_name, img_allure):     # 截图
        images_dir1 = os.path.dirname(root_path)
        images_dir2 = os.path.join(images_dir1, "images_log")
        os.makedirs(images_dir2, exist_ok=True)
        screenshot_path = os.path.join(images_dir2, f"{img_name}.png")

        try:
            if self.driver.get_screenshot_as_file(screenshot_path):
                allure.attach.file(screenshot_path, name=img_allure,
                                   attachment_type=allure.attachment_type.PNG)
                logger.debug(f'截取当前页面,保存图片"{screenshot_path}",并上传到 allure 中')
        except Exception as e:
            logger.debug(f'截图操作时发生错误"{e}"')
